//
//  JZh5View.m
//  tf02
//
//  Created by Jim on 16/8/18.
//  Copyright © 2016年 Jim. All rights reserved.
//

#import "JZh5View.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "AFNetworking.h"
#import "NSDictionary+JSONString.h"
#import "NSString+Hash.h"

static NSString *const estimatedProgress = @"estimatedProgress";

@interface JZh5View () <WKUIDelegate, WKNavigationDelegate, UIScrollViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong, readwrite) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UIButton *noNetView;
@property (nonatomic, assign, getter = isFirstLoad) BOOL firstLoad;

/**
 * 点击网络故障时刷新网页
 */
- (void)private_reloadWebPage;

@end

@implementation JZh5View

#pragma mark - 懒加载
- (UIButton *)noNetView
{
    if (!_noNetView) {
        UIButton *noNetView = [[UIButton alloc] initWithFrame:self.bounds];
        noNetView.backgroundColor = [UIColor whiteColor];
        noNetView.contentMode = UIViewContentModeCenter;
        [noNetView setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [noNetView setTitle:@"网络故障，点击刷新" forState:UIControlStateNormal];
        noNetView.titleLabel.font = [UIFont systemFontOfSize:15];
        [noNetView addTarget:self action:@selector(private_reloadWebPage) forControlEvents:UIControlEventTouchUpInside];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Failure"]];
        imageView.center = CGPointMake(noNetView.center.x, noNetView.center.y - 30);
        [noNetView addSubview:imageView];
        noNetView.hidden = YES;
        _noNetView = noNetView;
    }
    return _noNetView;
}

- (WKWebView *)webView
{
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:self.bounds];
        _webView.UIDelegate = self;
        _webView.contentMode = UIViewContentModeRedraw;
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _webView.navigationDelegate = self;

        _webView.allowsBackForwardNavigationGestures = YES;
        [_webView addObserver:self forKeyPath:estimatedProgress options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
//        _webView.scrollView.bounces = NO;
//        _webView.scrollView.bouncesZoom = NO;
        _webView.scrollView.delegate = self;
        _webView.multipleTouchEnabled = NO;

    }
    return _webView;
}

- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 3.f)];
        _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    }
    return _progressView;
}

#pragma mark - URLString setter 方法
- (void)setURLString:(NSString *)URLString
{
    _URLString = [URLString copy];
    
    NSURL *url = [NSURL URLWithString:URLString];
    
    NSURLRequest *request = [NSURLRequest requestWithURL: url];
    
    [self.webView loadRequest: request];
}

#pragma mark - UIView 系统方法
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.firstLoad = YES;
        
        [self addSubview:self.webView];
        
        [self addSubview:self.progressView];
        
        [self addSubview:self.noNetView];
        
    }
    return self;
}

#pragma mark - JZh5View 私有方法
- (void)private_reloadWebPage
{
    self.URLString = _URLString;
    
    if ([self.delegate respondsToSelector:@selector(wetherCollected:)]) {
        
        [self.delegate wetherCollected:self];
    }
}

#pragma mark - UIScrollViewDelegate 代理方法

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return nil;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x) {
        CGPoint offset = scrollView.contentOffset;
        offset.x = 0;
        scrollView.contentOffset = offset;
    }
}

#pragma mark - NSObject(NSKeyValueObserving) 方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
//    NSLog(@" %s,change = %@",__FUNCTION__,change);
    if ([keyPath isEqual:estimatedProgress] && object == self.webView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if(self.webView.estimatedProgress >= 1.0f)
        {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - 图片保存完毕的回调
//- (void)image:(UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo:(void *)contextInf {
//    NSLog(@"%s", __FUNCTION__);
//}
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
//{
//    NSLog(@"%s", __FUNCTION__);
//
//}
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
//{
//    NSLog(@"%s", __FUNCTION__);
//
//}
//- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
//{
//    NSLog(@"%s", __FUNCTION__);
//
//}

#pragma mark - WKNavigationDelegate 代理方法
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    _URLString = webView.URL.absoluteString;
    
    if ([_URLString isEqualToString:@"https://lnk0.com/cYl0Mp"]) {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"https://lnk0.com/cYl0Mp"]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://lnk0.com/cYl0Mp"]];
        }
    } else {
        self.noNetView.hidden = YES;

    }
    
    if ([self.delegate respondsToSelector:@selector(h5View:updateNewWebPageWithURL:)]) {
        
        [self.delegate h5View:self updateNewWebPageWithURL:_URLString];

    }
    
    NSLog(@"_URLString = %@", _URLString);
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    [self.progressView setProgress:webView.estimatedProgress animated:YES];
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    self.firstLoad = NO;
    
    [self.progressView setProgress:webView.estimatedProgress animated:YES];
}

// 页面开始加载时发生错误
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    self.noNetView.hidden = NO;
    if ([self.delegate respondsToSelector:@selector(h5View:didFailProvisionalNavigation:withError:)]) {
        
        [self.delegate h5View:self didFailProvisionalNavigation:navigation withError:error];
    }
}

// 页面提交时发生错误
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"页面提交时发生错误");
    if ([self.delegate respondsToSelector:@selector(h5View:didFailNavigation:withError:)]) {
        
        [self.delegate h5View:self didFailNavigation:navigation withError:error];
    }
    
}

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"接收到服务器跳转请求之后调用webView.URL = %@", webView.URL);
    
}

// 在发送请求之前，决定是否跳转
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
//{
//    NSLog(@"发送请求webView.URL = %@", [[webView.URL.absoluteString componentsSeparatedByString:@"?"] firstObject]);
//    NSString *URLString = [[navigationAction.request URL] absoluteString];
//
//    URLString = [URLString stringByRemovingPercentEncoding];
////    NSLog(@"URLString = %@",URLString);
//    // 用://截取字符串
//    NSArray *urlComps = [URLString componentsSeparatedByString:@"://"];
//    if ([urlComps count]) {
//        // 获取协议头
//        NSString *protocolHead = [urlComps objectAtIndex:0];
//        NSLog(@"protocolHead=%@",protocolHead);
//    }
//    decisionHandler(WKNavigationActionPolicyAllow);
//}

#pragma mark - dealloc 方法
- (void)dealloc
{
    [_webView removeObserver:self forKeyPath:estimatedProgress];

    // if you have set either WKWebView delegate also set these to nil here
    [_webView setNavigationDelegate:nil];
    [_webView setUIDelegate:nil];
    _webView.scrollView.delegate = nil;
}



@end
